<!DOCTYPE html>
<html>

	<head>
		<title>印章拖动示例</title>
		<!-- <link href="./css/jquery.zsign.css" rel="stylesheet" type="text/css" /> -->
		<!-- <script src="./js/jquery-1.7.1.min.js" type="text/javascript"></script> -->
		<script src="./js/polyfill.min.js" type="text/javascript"></script>
		<script src="./js/es6-promise.auto.min.js"></script>
		<script src="./js/jquery-3.3.1.min.js" type="text/javascript"></script>
		<script src="./js/pdfjs-dist/build/pdf.min.js"></script>
		<link type="text/css" rel="stylesheet" href="./css/bootstrap.min.css">
		<link type="text/css" rel="stylesheet" href="./css/sign.css">
		<link href="css/style.css" rel="stylesheet" />
		<script src="js/ui.js"></script>
	</head>

	<body>

		<div class="ui-h100">
			<div class="sign_warp">
				<div class="sign_content" id="signContainer"></div>
				<div class="sign_right">
					<div id="signList" class="signList"></div>
					<div class="seal-btn-wrapper">
						<button type="button" class="btn btn-danger btn-lg btn-block" onclick="submitSign()">确认签署</button>
					</div>
				</div>
			</div>
		</div>
		<script>
			var pdfjsLib = window['pdfjs-dist/build/pdf'];
			pdfjsLib.PDFJS.workerSrc = './js/pdfjs-dist/build/pdf.worker.js';
			pdfjsLib.PDFJS.cMapUrl = './js/pdfjs-dist/cmaps/';
			pdfjsLib.PDFJS.cMapPacked = true;
			var fileUrl = '';
			console.log(window.location)
			var pdfUrl = [];
			//文档视图数组
			var viewPortArray = [];
			//文档总页数
			var viewPagesNumber = '';
			//旋转次数
      var rotateTime = 1;
      var arr = location.search.slice(1).split('?');
      for (let item of arr) {
          let a = item.split('=');
            pdfUrl[a[0]] = a[1];
      }

			// 提交印章数组
			const posBean = [];
			// 默认文档
			let docsCurrentNumber = 0
			// 印章
			const sealList = [{
				sealImg: './seal/seal.png',
				sealId: '签署人标识'
			}]
			var urlObject = [];
debugger
            // 解析pdf
            var rendererPdf = function(docsNumber){

                // 获取文档方式
                const loadType =  docsList[docsNumber].loadType;
                // 获取文档值
                const docValue =  docsList[docsNumber].docValue;
                // PDF文件
                var pdfValue = null;

                if(loadType == "byBase64"){
                    // 通过文档编号从服务端获取PDF的Base64字符串
                    //var pdfBase64 = getPDFBase64ByAjax(docValue);
                    // 通过Base64获取PDF
                    var pdfBase64 = base64Con;
                    var pdfFileBinary = convertDataURIToBinary(pdfBase64);
                    pdfValue = pdfFileBinary;
                }else{
                    pdfValue = docValue;
                }

                // Asynchronous download of PDF
                var loadingTask = pdfjsLib.getDocument(pdfValue);
debugger
                // 解析pdf
              // setTimeout(function () {
                loadingTask.promise.then(function(pdf) {
                  console.log('PDF loaded');

                  console.log(pdf.numPages, '当前文档总页数');
                  viewPagesNumber = pdf.numPages;
                  // 遍历 pdf.numPages， 调用 renderer(pdf, n) 获取多文档展示

                  // Fetch the first page
                  // const pageNumber = 1;

                  for(let index = 1; index <= pdf.numPages; index++) {
                    debugger
                    rendererTemplate(index)
                    renderer(pdf, index)
                  }
                }, function(reason) {
                  // PDF loading error
                  console.error(reason);
                });
              // }, 5000)
            }

			// 文档列表
	        const docsList = [
	        {
	        	loadType: 'byBase64',
	            title: 'PDF文件Base64',
	            docValue: 'HT201808260001'

	        },
	        {
	        	loadType: 'byFilePath',
	            title: '相对路径',
	            // docValue: './pdf/test_Black.pdf'
	            docValue: pdfUrl.url
	        }
	        ]

            docsCurrentNumber = 1
            rendererPdf(1)

			// 初始化
			const init = function() {

				// 印章列表
				// sealList.forEach(item => {
        $.ajax({
            type:'get',
            url:window.parent.VUE_APP_BASE_URL + 'sign/base/yunSign/getCloudSignSealsBySealCode',
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function (resp) {
                resp.forEach(function (item) {
                    item.picB64  = 'data:image/png;base64,' + item.picB64;
                    urlObject.push(item.picB64);
                    const template =
                        '<div class="sealItems" style="background-image: url('+item.picB64+');" sealId= "' + item.sealId + '"  sealSn = "' + item.msg + '" draggable="true" ondragstart= \'_ondragstart(event, {sealImg: "urlObject", sealId: "' + item.sealId + '" , sealName:"'+item.name+'",sealSn:"'+item.msg+'"})\' ondragend= \'_ondragend(event)\'></div>'
                    $('#signList').append(template)
                });

            },
            error:function (resp) {
                console.log(resp)
            }
        })

				// 文档列表
				docsList.forEach(function(item, index){
					// 初始化 posBean
					posBean[index] = [];
				})
			}

			// 渲染印章
			const rendererSeal = function(pageNumber, pageViewOffsetHeight){
				posBean[docsCurrentNumber].length && posBean[docsCurrentNumber].forEach(function item(){
					if(item.posPage == pageNumber) {
						rendererSealTemplate(item, pageViewOffsetHeight)
					}
				})
			}

			// 渲染 pages
			const renderer = function(pdf, pageNumber,rotateTimes){
  debugger
				pdf && pdf.getPage(pageNumber).then(function(page) {
					console.log('Page loaded');
					console.log(page, 'page')

					// pdf 解析的比例， 获取原始文档尺寸 scale = 1; 如果文档放大，印章x y 需要同比例缩放
					var scale = 2;
          for (let i = 0; i < page.view.length; i++) {
            if (page.view[i]>2000){
              scale= 0.4
            }
          }
					debugger
					var viewport = page.getViewport(scale);
					if(rotateTimes){
                        viewport = page.getViewport(scale,rotateTimes*120);
					}
					debugger
                    viewPortArray.push(viewport);

					// Prepare canvas using PDF page dimensions
					// 遍历 pdf.numPages， 传递 不同的 Canvas ID
					var canvas = document.getElementById('pageCanvas_' + pageNumber);
					console.log(canvas, '')
					var context = canvas.getContext('2d');

					// 设置 canvas
					canvas.height = viewport.height;
					canvas.width = viewport.width;
                    canvas.style.height = viewport.height/scale + 'px'
                    canvas.style.width = viewport.width/scale + 'px'

					// 设置外层大小

					var pageView = document.getElementById('pageView_' + pageNumber)
					pageView.style.height = viewport.height/scale + 'px'
					pageView.style.width = viewport.width/scale + 'px'
          // if (scale==0.3){
          //   pageView.style.height = viewport.height*scale + 'px'
          //   pageView.style.width = viewport.width*scale + 'px'
          //   canvas.style.height = viewport.height*scale + 'px'
          //   canvas.style.width = viewport.width*scale + 'px'
          // }
					// Render PDF page into canvas context
					page.render({
						canvasContext: context,
						viewport: viewport
					}).then(function() {
						// 渲染印章
						console.log('Page rendered');
						if(!rotateTimes){
						  debugger
                            rendererSeal(pageNumber, pageView.offsetHeight)
						}
						console.log('PageSeal rendered');
					}, function err() {
						console.log('Page error');
					});
				});
			}

			// 新增dom
			const rendererTemplate = function(pageNumber){
				const template =
					"<div id='pageView_" + pageNumber + "' class='pageView' ondragenter = '_ondragenter(event)' ondragover = '_ondragover(event)' ondragleave = '_ondragleave(event)' ondrop = '_ondrop(event," + pageNumber + ")'><canvas id='pageCanvas_" + pageNumber + "' class='pageCanvas'></canvas></div>"
				$('#signContainer').append(template)
        debugger
			}

			// 新增印章dom
			const rendererSealTemplate = function(dragData, pageViewOffsetHeight){
                dragData.sealImg = urlObject[0];
				const template = "<div id='drag" + dragData.id + "' class='sealView' style='width:" + dragData.width + "px; height:" + dragData.height + "px; left: " + (dragData.posX - (dragData.width/2)) + "px; top: " + (pageViewOffsetHeight - (dragData.height/2) - dragData.posY) + "px; background-image: url(" + dragData.sealImg + ");'><button class='sealDel' onclick='delSealItem(\"" + dragData.id + "\")'>删除</button></div>"
				$("#pageView_" + dragData.posPage).append(template)
        debugger
			}

			// 删除印章
			const delSealItem = function(id){
				for(let index = 0; index < posBean[docsCurrentNumber].length; index++) {
					if(posBean[docsCurrentNumber][index]['id'] == id) {
						posBean[docsCurrentNumber].splice(index, 1)
						break
					}
				}
				$("#drag" + id).remove()
			}

			// 切换文档
			var changeDocs = function(event, docsNumber){
				$(event.target).addClass('current').siblings().removeClass('current')
				$('#signContainer').html('')
				docsCurrentNumber = docsNumber
				rendererPdf(docsNumber)
			}

			//将encodeBase64解码
		 	convertDataURIToBinary = function(dataURI){
                    var raw = window.atob(dataURI);
                    var rawLength = raw.length;
                    //转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068
                    var array = new Uint8Array(new ArrayBuffer(rawLength));
                    for (i = 0; i < rawLength; i++) {
                        array[i] = raw.charCodeAt(i);
                    }
                    return array;
                }

				getPDFBase64ByAjax = function(fileCode){
					var fileBase64 = null;
                    $.ajax({
                        type: "POST",
                        url: "http://localhost:8080/JavaPDFViewByBase64/get_base64",
                        data: {
                            filecode:fileCode
                        },
                        dataType: "json",
                        async:false,
                        success: function(data) {
                        	if(null == data){
                        		alert('请求获取文件Base64的响应结果为空');
                        	}else{
                        		var errCode = data.errCode;
                        		if(0 == errCode){
                        			fileBase64 = data.base64;
                        		}else{
                        			alert('获取文件Base64字符串失败');
                        		}
                        	}
                        }
                    });
                    return fileBase64;
                }

			// 初始化列表+印章
			init()
			// 初始化第一份文档
			// rendererPdf(docsCurrentNumber)

			// 确认签署
			const submitSign = function(){
				//console.log(posBean, '确认签署');

				// 前端显示印章对应的坐标信息
				// mizhu.alert('印章中心点坐标信息JSON字符串', JSON.stringify(posBean));
				var queryParams = {
				    type:'signType',
				    sign:posBean,
                    rotateTimes:rotateTime
				}

                window.parent.postMessage(JSON.stringify(queryParams),'*');

			}

			//旋转pdf
			function rotatePdf() {
                //只有一页的时候可以旋转
				if(viewPagesNumber === 1){
                    var loadingTask = pdfjsLib.getDocument(docsList[1].docValue);

                    // 解析pdf
                    loadingTask.promise.then(function(pdf) {
                        console.log('PDF loaded');

                        console.log(pdf.numPages, '当前文档总页数');
                        viewPagesNumber = pdf.numPages;
                        // 遍历 pdf.numPages， 调用 renderer(pdf, n) 获取多文档展示

                        // Fetch the first page
                        // const pageNumber = 1;
                        for(let index = 1; index <= pdf.numPages; index++) {
                            // rendererTemplate(index)
                            renderer(pdf, index, rotateTime)
                        }
                        rotateTime ++;

                    }, function(reason) {
                        // PDF loading error
                        console.error(reason);
                    });
				}else{
                    top.layer.msg('只支持一页文档旋转！')
				}
            }

			// 拖拽事件
			// 触发源
			var _ondragstart = function(event, sealData){
				console.log('start');
				// 或者通过获取 sealId 遍历检索相应的对象获取印章数据
				console.log(event.target.getAttribute('sealId'));

				const pos = {
					'posX': 0, // 签署位置横坐标
					'posY': 0, // 签署位置纵坐标
				};

				const dragData = Object.assign(pos, sealData);

				event.dataTransfer.setData('Text', JSON.stringify(dragData));

				//  IE下没有 setDragImage 这个属性
				if(event.dataTransfer.setDragImage) {
					// 设置鼠标位置
					event.dataTransfer.setDragImage(event.target, 50, 50);
				}
			}

			var _ondragend = function(event){
				console.log('end');
			}

			// 目标源
			var _ondragenter = function(event){
				console.log('enter');
			}

			var _ondragover = function(event){
				event.preventDefault();
				event.stopPropagation();
				console.log('over');
			}

			var _ondragleave = function(event){
				console.log('leave');
			}

			var _ondrop = function(event, page){
  debugger
				event.preventDefault();
				event.stopPropagation();
				console.log('drop');

				const dragData = JSON.parse(event.dataTransfer.getData('Text'));

				const pdf = document.getElementById('signContainer')
				const pageView = document.getElementById('pageView_' + page)
				dragData.posX = event.pageX - pdf.offsetLeft - pageView.offsetLeft + pdf.scrollLeft
				dragData.posY = pageView.offsetHeight - (event.pageY - (pdf.offsetTop + pageView.offsetTop - pdf.scrollTop))
				// 存储提交印章
        debugger

				dragData.posPage = page
				dragData.width = dragData.width || 100;
				dragData.height = dragData.height || 100;
        if (event.currentTarget.clientHeight > 2000 || event.currentTarget.clientWidth > 2000) {
          dragData.width = dragData.width/0.4 || 100/0.4;
          dragData.height = dragData.height/0.4 || 100/0.4;
        }
				dragData.id = 'seal_' + Date.parse(new Date())
                posBean[docsCurrentNumber] = [];
				posBean[docsCurrentNumber].push(dragData)
				console.log(dragData, '印章签署相关信息');
				console.log(posBean, 'posBean');

				// 或者直接组装dom，append 插入到 pageView_1
				rendererSealTemplate(dragData, pageView.offsetHeight)
				// const seal_1 = document.getElementById('seal_1')
				// 	  seal_1.style.width = dragData.width + 'px'
				// 	  seal_1.style.height = dragData.height + 'px'
				// 	  seal_1.style.left = dragData.posX - (dragData.width/2) + 'px'
				// 	  seal_1.style.top = pageView.offsetHeight - (dragData.height/2) - dragData.posY + 'px'
				// 	  seal_1.style.backgroundImage = `url(${dragData.sealImg})`
			}
		</script>
	</body>

</html>
